//
//  SaveController.swift
//  DSP
//
//  Created by tucici on 2024/5/23.
//

import UIKit
import TCCKit
import RealmSwift
let EDITBINKEY = "editBinKey"
class SaveController: DSAlertController {
    private var bgView : UIView!
    private var basicBtn : SaveItem!
    private var advanceBtn : SaveItem!
    private var line : UIView!
    private var line2 : UIView!
    private var pwd = ""
    private var localPWD = ""{
        didSet{
            UserDefaults.standard.setValue(localPWD, forKey: EDITBINKEY)
            UserDefaults.standard.synchronize()
        }
    }
    private var select_index = 10000
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initData()
    }
    
    override func initUI() {
        
        bgView = UIView()
        bgView.bgHexColor = "#FFFFFF"
        bgView.cornerRadius = 10.k_h
        
        basicBtn = SaveItem()
        basicBtn.img.image = UIImage(named: "files")
        basicBtn.title.text = "Basic Tuning Presets"
        basicBtn.addTarget(self, action: #selector(actionForItem), for: .touchUpInside)
        
        advanceBtn = SaveItem()
        advanceBtn.img.image = UIImage(named: "files")
        advanceBtn.title.text = "Adavnced Tuning Presets"
        advanceBtn.addTarget(self, action: #selector(actionForItem), for: .touchUpInside)
        
        line = UIView()
        line.bgHexColor = "#000000"
        
        line2 = UIView()
        line2.bgHexColor = "#000000"
        
        tableViewStyle = .grouped
        tableView.backgroundColor = "#FFFFFF".color()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SaveCell.self, forCellReuseIdentifier: SaveCell.ID())
        
        view.addSubview(bgView)
        bgView.addSubview(basicBtn)
        bgView.addSubview(advanceBtn)
        bgView.addSubview(line)
        bgView.addSubview(line2)
        bgView.addSubview(tableView)
        
        bgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(k_w(30))
            make.top.bottom.equalToSuperview().inset(k_h(70))
        }
        
        basicBtn.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.right.equalTo(line.snp.left)
            make.height.equalTo(50)
        }
        
        advanceBtn.snp.makeConstraints { make in
            make.right.top.equalToSuperview()
            make.left.equalTo(line.snp.right)
            make.height.equalTo(50)
        }
        
        line.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 1, height: 50))
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        line2.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom)
            make.left.right.equalToSuperview().inset(10)
            make.height.equalTo(1)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(line2.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    private var array = [ChannelManager](){
        didSet{
            tableView.reloadData()
        }
    }
    
    override func initData(){
        localPWD = UserDefaults.standard.value(forKey: EDITBINKEY) as? String ?? ""
        // array = RealmHelper.queryObject(objectClass:ChannelManager()).map{$0.copy() as! ChannelManager}
        array = RealmHelper.queryObject(objectClass:ChannelManager())
        
    }
    
    ///更新本地数据
    private func update(_ model:ChannelManager){
        try! RealmHelper.realm.write({
            //            for manager in array{
            //                manager.select = model == manager
            //            }
        })
        
        RealmHelper.updateObjects(objects: array)
        initData()
    }
    
    ///新建保存
    private func save(_ text:String, needPwd:Bool){
        let ch_manager = APP.CHM.copy() as! ChannelManager
        ch_manager.name = text
        ch_manager.date = Date.date(formatter: "yyyy-MM-dd HH:mm:ss")
        ch_manager.pwd = needPwd ? pwd : ""
        array.append(ch_manager)
        update(ch_manager)
    }
    
    ///删除
    private func delete(_ model:ChannelManager){
        if model.isLock && pwd == ""{
            showAlert(2,false,completion: {[weak self] in
                self?.delete(model)
            })
            return
        }
        
        RealmHelper.deleteObject(object: model)
        initData()
    }
    
    
    ///分享
    private func share(_ model:ChannelManager){
        if model.isLock && pwd == ""{
            showAlert(2,false,completion: { Share.share(model)})
            return
        }
        Share.share(model)
    }
    
    ///选中
    private func select(_ model:ChannelManager){
        if model.isLock && pwd == ""{
            showAlert(2,false,completion: {[weak self] in
                self?.select(model)
            })
            return
        }
        //update(model)
        APP.CHM = model.copy() as! ChannelManager
        APP.upload(model)
        hidden()
    }
    
    ///修改密码
    private func chanagePwd(completion:(()->Void)?){
        let pvc = PWDController()
        pvc.type = .reset
        present(pvc, animated: false)
        pvc.block = {[weak self] (text1,text2,text3) in
            if text1 != self?.localPWD ?? ""{
                CLHUD("The old password is incorrect",type: .error,time:1.5, callBack: nil)
                return false
            }
            self?.localPWD = text2
            self?.pwd = text2
            ///这里特意要等1.5s，要等PWDController完全退出再调用completion，不然completion里的弹窗不会弹出来
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                completion?()
            })
            return true
        }
    }
    
    @objc func actionForItem(sender:SaveItem?){
        if sender == basicBtn{
            showAlert(3, false, completion: nil)
        }else{
            if localPWD == ""{
                showAlert(1,false,completion: {[weak self] in
                    self?.showAlert(3, true, completion: nil)
                })
            }else if localPWD.count > 0 && localPWD != pwd{
                showAlert(2,false,completion: {[weak self] in
                    self?.showAlert(3, true, completion: nil)
                })
            }
        }
    }
    
    ///弹出相关提示框
    private func showAlert(_ type:Int, _ needPwd:Bool, completion: (()->Void)?){
        switch type{
        case 1:///从没有设置过密码
            let pvc = PWDController()
            pvc.type = .set
            present(pvc, animated: false)
            pvc.block = {[weak self] (_,text2,text3) in
                if text2.count < 6 || text2.count > 12{
                    CLHUD("The password is between 6~12 characters",type: .error,time:1.5, callBack: nil)
                    return false
                }else if !text2.isNumberOrAlphabet(){
                    CLHUD("Only numbers or characters",type: .error,time:1.5, callBack: nil)
                    return false
                }
                self?.localPWD = text2
                self?.pwd = text2
                self?.tableView.reloadData()
                
                ///这里特意要等1.5s，要等PWDController完全退出再调用completion，不然completion里的弹窗不会弹出来
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                    completion?()
                })
                return true
            }
        case 2:///设置过密码，本次没有输入过密码
            let vc = AlertController()
            vc.msg.text = "Please enter your password"
            vc.tips.text = "Change your password"
            vc.style = .input
            present(vc, animated: false)
            vc.rightBlock = {[weak self] text in
                if text != self?.localPWD ?? ""{
                    CLHUD("The password is incorrect",type: .error,time:1.5, callBack: nil)
                    return
                }
                self?.pwd = text
                completion?()
            }
            vc.tipsBlock = {[weak self] in
                self?.chanagePwd(completion: completion)
            }
        case 3:///本次密码 == 存储密码  ｜｜  没有密码
            title = "New Settings"
            let vc = AlertController()
            vc.msg.text = "New Settings"
            vc.style = .input
            present(vc, animated: false)
            vc.rightBlock = {[weak self] text in
                self?.save(text, needPwd: needPwd)
            }
            vc.tipsBlock = {[weak self] in
                self?.chanagePwd(completion: completion)
            }
        default:
            break
        }
    }
}

//MARK: - UITableViewDataSource
extension SaveController:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SaveCell.ID()) as! SaveCell
        let model = array[indexPath.row]
        cell.model = model
        cell.line.isHidden = indexPath.row == array.count - 1
        cell.bgHexColor = select_index == indexPath.row ? HEX_RED : HEX_WHITE
        cell.block = {[weak self] in
            self?.share(model)
        }
        return cell
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        delete(array[indexPath.row])
    }
}
//MARK: - UITableViewDelegate
extension SaveController:UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if array[indexPath.row].select {return}
        select(array[indexPath.row])
        select_index = indexPath.row
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "Delete"
    }
}
